<script setup>
import { ref, watch, nextTick, computed } from 'vue'
import { addBank } from '@/api/bank'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { getBankInfoByCardNumber } from '@/constants/bank'

const props = defineProps({
  bankData: {
    type: Object,
    default: null,
  },
})

const emit = defineEmits(['success', 'cancel'])

const formRef = ref(null)
const formData = ref({
  dealerBankId: '',
  bank: '',
  bankCode: '',
  bankName: '',
  status: 0,
})

const bankInfo = computed(() => {
  return getBankInfoByCardNumber(formData.value.bankCode)
})

const rules = {
  bank: [{ required: true, message: '请输入开户行', trigger: 'blur' }],
  bankName: [{ required: true, message: '请输入户名', trigger: 'blur' }],
  bankCode: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

watch(
  () => props.bankData,
  (newVal) => {
    nextTick(() => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      if (newVal) {
        formData.value = { ...newVal }
      } else {
        formData.value = {
          dealerBankId: '',
          bank: '',
          bankCode: '',
          bankName: '',
          status: 0,
        }
      }
    })
  },
  { immediate: true, deep: true },
)

watch(
  () => formData.value.bankCode,
  (newVal) => {
    if (newVal) {
      const info = getBankInfoByCardNumber(newVal)
      if (info.name !== '未知银行') {
        formData.value.bank = info.name
      }
    }
  },
)

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addBank(formData.value)
        if (res.success) {
          ElMessage.success(formData.value.dealerBankId ? '编辑成功' : '添加成功')
          emit('success')
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        logger.error('操作失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}
</script>

<template>
  <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
    <el-form-item label="开户行" prop="bank">
      <el-input v-model="formData.bank" placeholder="请输入开户行或根据卡号自动识别"></el-input>
    </el-form-item>
    <el-form-item label="户名" prop="bankName">
      <el-input v-model="formData.bankName" placeholder="请输入户名"></el-input>
    </el-form-item>
    <el-form-item label="银行卡号" prop="bankCode">
      <el-input v-model="formData.bankCode" placeholder="请输入银行卡号">
        <template #prepend>
          <div class="bank-identifier">
            <img v-if="bankInfo.logo" :src="bankInfo.logo" alt="logo" class="bank-logo-small" />
            <span>{{ bankInfo.name }}</span>
          </div>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-radio-group v-model="formData.status">
        <el-radio :label="0">启用</el-radio>
        <el-radio :label="1">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.bank-identifier {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 140px;

  .bank-logo-small {
    width: 24px;
    height: 24px;
    border-radius: 50%;
  }
}
</style>
